package net.hn.hnms.biz.plan.group.service.impl;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.api.plan.RemotePlanService;
import net.hn.hnms.biz.plan.domain.*;
import net.hn.hnms.biz.plan.group.service.GroupService;
import net.hn.hnms.biz.plan.group.service.GroupStatisticService;
import net.hn.hnms.biz.plan.mapper.*;
import net.hn.hnms.biz.plan.request.*;
import net.hn.hnms.biz.plan.vo.*;
import net.hn.hnms.sys.common.core.constant.MineBaseConstants;
import net.hn.hnms.sys.common.core.enums.CoalInfo;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.system.api.RemoteDeptService;
import net.hn.hnms.sys.system.api.domain.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service("groupService")
@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection"})
public class GroupServiceImp implements GroupService {


    @Autowired
    private RemotePlanService remotePlanService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private GroupSaleGatherMapper groupSaleGatherMapper;

    @Autowired
    private GroupDataGatherMapper groupDataGatherMapper;

    @Autowired
    private GroupYieldProductionMapper groupYieldProductionMapper;

    @Autowired
    private GroupFootageMapper groupFootageMapper;

    @Autowired
    private PlanMiningMapper planMiningMapper;

    @Autowired
    private PlanDrivageMapper planDrivageMapper;

    @Autowired
    private PlanWashingMapper planWashingMapper;

    @Autowired
    private PlanOtherMapper planOtherMapper;

    @Autowired
    private DimDrivageFaceMapper dimDrivageFaceMapper;

    @Autowired
    private DimMiningFaceMapper dimMiningFaceMapper;

    @Autowired
    private PlanOutputMapper planOutputMapper;

    @Autowired
    private ExecutionFootageOutputMapper footageOutputMapper;

    @Autowired
    private ExecutionOtherMapper otherMapper;

    @Autowired
    private ExecutionWashingMapper washingMapper;

    @Autowired
    private ExecutionCostMapper costMapper;

    @Autowired
    private GroupStatisticMapper groupStatisticMapper;

    @Autowired
    private GroupStatisticService groupStatisticService;


    /**
     * 保存龙软数据
     *
     * @param date
     * @return
     * @throws Exception
     */
    @Override
    public int insertSale(String date) throws Exception {

        String dates = date == null ? DateUtils.getDate() : date;
//        String output = remotePlanService.getSaleStatsticData(dates);
        String url = "http://10.103.9.31/PDDP/PDDPAPI/GetSaleStatsticData?date=" + dates;
        String output = sendGet(url);
        log.info("Response content: " + output);
        if (output != null) {
            //解析Json
            JSONObject jsonobj = JSON.parseObject(output); //将json字符串转换成jsonObject对象
            if (jsonobj != null) {
                if (jsonobj.getInteger("Code") == 200) {

                    GroupDataGather groupDataGather = new GroupDataGather();
                    groupDataGather.setDataDate(dates);//数据时间
                    groupDataGather.setType("1");//1 代表销量
                    groupDataGather.setData(output);//json 数据
                    LambdaQueryWrapper<GroupDataGather> w = new LambdaQueryWrapper<>();
                    w.eq(GroupDataGather::getDataDate, date).eq(GroupDataGather::getType, "1");
                    groupDataGatherMapper.delete(w);
                    groupDataGatherMapper.insert(groupDataGather);

                    System.out.println(jsonobj.get("Data"));
                    JSONObject Data = jsonobj.getJSONObject("Data");
                    String yoy = Data.getString("YOY");
                    JSONArray list = Data.getJSONArray("Sale");
//                    JSONArray TwoYear = Data.getJSONArray("TwoYear");
                    JSONArray YearPlan = Data.getJSONArray("YearPlan");
                    JSONArray MonthPlan = Data.getJSONArray("MonthPlan");
                    JSONObject object = JSONObject.parseObject(Data.getString("JiTuanSale"));

//                    GroupSaleTotalGather jiTuanSale = JSON.parseObject(ji, GroupSaleTotalGather.class);
//                    GroupSaleTotalGather jiTuanSale = JsonUtils.parseObject(Data.getString("JiTuanSale"), GroupSaleTotalGather.class);
//                    jiTuanSale.setDataDate(dates);
                    List<GroupSaleGather> carInspects = list.toJavaList(GroupSaleGather.class);
//                    List<GroupTwoYearGather> twoYear = TwoYear.toJavaList(GroupTwoYearGather.class);
                    List<GroupSaleGather> yearPlan = YearPlan.toJavaList(GroupSaleGather.class);
                    List<GroupSaleGather> monthPlan = MonthPlan.toJavaList(GroupSaleGather.class);

                    carInspects.stream().distinct().forEach(item -> {
                        item.setDataDate(dates);
                        item.setYoy(yoy);

                        for (GroupSaleGather yieldYearPlan : yearPlan) {
                            if (yieldYearPlan.getName().equals(CoalInfo.getMineNameById(item.getDeptId()))) {
                                item.setYearPlan(yieldYearPlan.getYearPlan());

                                break;
                            }
                        }
                        for (GroupSaleGather yieldMonthPlan : monthPlan) {
                            if (yieldMonthPlan.getName().equals(CoalInfo.getMineNameById(item.getDeptId()))) {
                                item.setMonthPlan(yieldMonthPlan.getMonthPlan());
                                break;
                            }
                        }
                        item.setName(CoalInfo.getMineNameById(item.getDeptId()));
                        item.setType(CoalInfo.getTypeByMineName(item.getName()));
                        item.setMineCode(CoalInfo.getMineCodeById(item.getDeptId()));
                        item.setCompanyCode(CoalInfo.getCompanyCodeById(item.getDeptId()));
                        item.setYearQuantitySum(new BigDecimal(object.getString("YearQuantitysum")));
                        item.setMonthQuantitySum(new BigDecimal(object.getString("MonthQuantitysum")));
                        item.setPrvQuantitySum(new BigDecimal(object.getString("PrvQuantitysum")));
                        item.setTodayQuantitySum(new BigDecimal(object.getString("TodayQuantitysum")));
                        item.setMonthPlanSum(new BigDecimal(object.getString("MonthPlansum")));
                        item.setDayAvg(new BigDecimal(object.getString("DayAvg")));
                    });

                    LambdaQueryWrapper<GroupSaleGather> galeW = new LambdaQueryWrapper<>();
                    galeW.eq(GroupSaleGather::getDataDate, date);
                    groupSaleGatherMapper.delete(galeW);
                    groupSaleGatherMapper.insertBatch(carInspects);
                }
            }
        }
        return 0;
    }

    public static String sendGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为 GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("Response code: " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }


    @Override
    public int insertOutput(String date) throws Exception {
        String dates = date == null ? DateUtils.getDate() : date;
//        String output = remotePlanService.getProductionData(date);
        String url = "http://10.103.9.31/PDDP/PDDPAPI/GetProductionData?date=" + dates;
        String output = sendGet(url);
        log.info("Response content: " + output);
//        output = null;

        if (output != null) {
            //解析Json
            JSONObject jsonobj = JSON.parseObject(output); //将json字符串转换成jsonObject对象
            if (jsonobj != null) {
                if (jsonobj.getInteger("Code") == 200) {
                    GroupDataGather groupDataGather = new GroupDataGather();
                    groupDataGather.setDataDate(dates);//数据时间
                    groupDataGather.setType("2");//2 代表产量
                    groupDataGather.setData(output);//json 数据
                    LambdaQueryWrapper<GroupDataGather> w = new LambdaQueryWrapper<>();
                    w.eq(GroupDataGather::getDataDate, date).eq(GroupDataGather::getType, "2");
                    groupDataGatherMapper.delete(w);
                    groupDataGatherMapper.insert(groupDataGather);

                    System.out.println(jsonobj.get("Data"));
                    JSONObject Data = jsonobj.getJSONObject("Data");
                    String yoy = Data.getString("YOY");
                    JSONArray list = Data.getJSONArray("Production");
//                    JSONArray TwoYear = Data.getJSONArray("TwoYear");
                    JSONArray YearPlan = Data.getJSONArray("YearPlan");
                    JSONArray MonthPlan = Data.getJSONArray("MonthPlan");
                    JSONObject object = JSONObject.parseObject(Data.getString("JiTuanProduction"));
                    List<YieldProduction> carInspects = list.toJavaList(YieldProduction.class);
                    List<YieldProduction> yearPlan = YearPlan.toJavaList(YieldProduction.class);
                    List<YieldProduction> monthPlan = MonthPlan.toJavaList(YieldProduction.class);
                    carInspects.stream().distinct().forEach(item -> {
                        item.setDataDate(dates);
                        item.setYoy(yoy);

                        for (YieldProduction yieldYearPlan : yearPlan) {
                            if (yieldYearPlan.getName().equals(item.getName())) {
                                item.setYearPlan(yieldYearPlan.getYearPlan());
                                break;
                            }
                        }
                        for (YieldProduction yieldMonthPlan : monthPlan) {
                            if (yieldMonthPlan.getName().equals(item.getName())) {
                                item.setMonthPlan(yieldMonthPlan.getMonthPlan());
                                break;
                            }
                        }
                        item.setType(CoalInfo.getTypeByMineName(item.getName()));
                        item.setMineCode(CoalInfo.getMineCodeByMineName(item.getName()));
                        item.setCompanyCode(CoalInfo.getCompanyCodeByMineName(item.getName()));
                        item.setYearQuantitySum(new BigDecimal(object.getString("YearQuantitysum")));
                        item.setMonthQuantitySum(new BigDecimal(object.getString("MonthQuantitysum")));
                        item.setPrvQuantitySum(new BigDecimal(object.getString("PrvQuantitysum")));
                        item.setTodayQuantitySum(new BigDecimal(object.getString("TodayQuantitysum")));
                        item.setMonthPlanSum(new BigDecimal(object.getString("MonthPlansum")));
                        item.setDayAvg(new BigDecimal(object.getString("DayAvg")));
                    });
                    LambdaQueryWrapper<YieldProduction> yiledW = new LambdaQueryWrapper<>();
                    yiledW.eq(YieldProduction::getDataDate, date);
                    groupYieldProductionMapper.delete(yiledW);
                    groupYieldProductionMapper.insertBatch(carInspects);
                }
            }
        }
        return 0;
    }

    @Override
    public int insertFootage(String date) throws Exception {
        String dates = date == null ? DateUtils.getDate() : date;
        String url = "http://10.103.9.31/PDDP/PDDPAPI/GetFootageData?date=" + dates;
        String output = sendGet(url);
        log.info("Response content: " + output);
//        output = null;

        if (output != null) {
            //解析Json
            JSONObject jsonobj = JSON.parseObject(output); //将json字符串转换成jsonObject对象
            if (jsonobj != null) {
                if (jsonobj.getInteger("Code") == 200) {
                    GroupDataGather groupDataGather = new GroupDataGather();
                    groupDataGather.setDataDate(dates);//数据时间
                    groupDataGather.setType("3");//3 代表进尺
                    groupDataGather.setData(output);//json 数据
                    LambdaQueryWrapper<GroupDataGather> w = new LambdaQueryWrapper<>();
                    w.eq(GroupDataGather::getDataDate, date).eq(GroupDataGather::getType, "3");
                    groupDataGatherMapper.delete(w);
                    groupDataGatherMapper.insert(groupDataGather);

                    System.out.println(jsonobj.get("Data"));
                    JSONObject Data = jsonobj.getJSONObject("Data");
                    String JGKYOY = Data.getString("JGKYOY");
                    String LTKYOY = Data.getString("LTKYOY");
                    JSONArray list = Data.getJSONArray("TunnelAndStrip");
                    JSONArray YearPlan = Data.getJSONArray("YearPlan");
                    JSONArray MonthPlan = Data.getJSONArray("MonthPlan");
                    JSONObject JiTuanFoot = JSONObject.parseObject(Data.getString("JiTuanFoot"));
                    JSONObject JGK = JSONObject.parseObject(JiTuanFoot.getString("JGK"));
                    JSONObject LTK = JSONObject.parseObject(JiTuanFoot.getString("LTK"));
                    List<GroupFootage> carInspects = list.toJavaList(GroupFootage.class);
                    //TODO 等龙软添加年计划字段
                    List<GroupFootage> yearPlan = YearPlan.toJavaList(GroupFootage.class);
                    List<GroupFootage> monthPlan = MonthPlan.toJavaList(GroupFootage.class);

                    carInspects.stream().distinct().forEach(item -> {
                        item.setDataDate(dates);
                        item.setLtkYoy(LTKYOY);
                        item.setJgkYoy(JGKYOY);

                        for (GroupFootage yieldYearPlan : yearPlan) {
                            if (yieldYearPlan.getName().equals(item.getName())) {
                                item.setYearPlan(yieldYearPlan.getYearPlan());
                                break;
                            }
                        }
                        for (GroupFootage yieldMonthPlan : monthPlan) {
                            if (yieldMonthPlan.getName().equals(item.getName())) {
                                item.setMonthPlan(yieldMonthPlan.getMonthPlan());
                                break;
                            }
                        }

                        item.setType(CoalInfo.getTypeByMineName(item.getName()));
                        item.setTypeName(item.getType().equals("1") ? "露天矿" : item.getType().equals("2") ? "井工矿" : "");
                        item.setMineCode(CoalInfo.getMineCodeByMineName(item.getName()));
                        item.setCompanyCode(CoalInfo.getCompanyCodeByMineName(item.getName()));
                        item.setJgkYearQuantitySum(new BigDecimal(JGK.getString("YearQuantitysum")));
                        item.setJgkMonthQuantitySum(new BigDecimal(JGK.getString("MonthQuantitysum")));
                        item.setJgkPrvQuantitySum(new BigDecimal(JGK.getString("PrvQuantitysum")));
                        item.setJgkTodayQuantitySum(new BigDecimal(JGK.getString("TodayQuantitysum")));
                        item.setJgkMonthPlanSum(new BigDecimal(JGK.getString("MonthPlansum")));
                        item.setJgkDayAvg(new BigDecimal(JGK.getString("DayAvg")));


                        item.setLtkYearQuantitySum(new BigDecimal(LTK.getString("YearQuantitysum")));
                        item.setLtkMonthQuantitySum(new BigDecimal(LTK.getString("MonthQuantitysum")));
                        item.setLtkPrvQuantitySum(new BigDecimal(LTK.getString("PrvQuantitysum")));
                        item.setLtkTodayQuantitySum(new BigDecimal(LTK.getString("TodayQuantitysum")));
                        item.setLtkMonthPlanSum(new BigDecimal(LTK.getString("MonthPlansum")));
                        item.setLtkDayAvg(new BigDecimal(LTK.getString("DayAvg")));
                    });
                    LambdaQueryWrapper<GroupFootage> yiledW = new LambdaQueryWrapper<>();
                    yiledW.eq(GroupFootage::getDataDate, date);
                    groupFootageMapper.delete(yiledW);
                    groupFootageMapper.insertBatch(carInspects);
                }
            }
        }
        return 0;
    }

    @Transactional
    @Override
    public int getMonthlyAssessmentRanking() throws Exception {
//        String dates = date == null ? DateUtils.getDate() : date;
        String url = "http://10.244.131.192:9000/monthlyAssessment/monthlyAssessment/listDp";
        String output = sendGet(url);
//        String output = "{\"success\":true,\"message\":\"操作成功！\",\"code\":200,\"result\":[{\"date\":\"2024-07-27\",\"score\":100.00,\"rank\":1,\"id\":\"1828351513690599426\",\"sysOrgCode_dictText\":\"华能煤业有限公司陕西矿业分公司\",\"totalScore\":\"100\",\"createBy\":\"xxgs0365\",\"hide\":0,\"createTime\":\"2024-08-27 16:39:05\",\"underreporting\":0,\"sysOrgCode\":\"A03A01A04\",\"remarks\":\"测试\"},{\"date\":\"2024-07-27\",\"score\":100.00,\"rank\":1,\"id\":\"1828360651552305153\",\"sysOrgCode_dictText\":\"扎赉诺尔煤业有限责任公司\",\"totalScore\":\"100\",\"createBy\":\"xxgs0365\",\"hide\":0,\"createTime\":\"2024-08-27 17:15:23\",\"underreporting\":0,\"sysOrgCode\":\"A03A01A05\",\"remarks\":\" 测试 123\"},{\"date\":\"2024-07-27\",\"score\":99.90,\"rank\":5,\"id\":\"1828360804438880258\",\"sysOrgCode_dictText\":\"华能庆阳煤电有限责任公司\",\"totalScore\":\"100\",\"createBy\":\"xxgs0365\",\"hide\":0,\"createTime\":\"2024-08-27 17:16:00\",\"underreporting\":0,\"sysOrgCode\":\"A03A01A06\",\"remarks\":\" 庆阳\"},{\"date\":\"2024-07-27\",\"score\":100.00,\"rank\":1,\"id\":\"1828360969690263553\",\"sysOrgCode_dictText\":\"华能云南滇东能源有限责任公司矿业分公司\",\"totalScore\":\"96\",\"createBy\":\"xxgs0365\",\"hide\":0,\"createTime\":\"2024-08-27 17:16:39\",\"underreporting\":0,\"sysOrgCode\":\"A03A01A08\"},{\"date\":\"2024-07-27\",\"score\":99.95,\"rank\":4,\"id\":\"1828361671439265794\",\"sysOrgCode_dictText\":\"华亭煤业集团有限责任公司\",\"totalScore\":\"95\",\"createBy\":\"xxgs0365\",\"hide\":0,\"createTime\":\"2024-08-27 17:19:26\",\"underreporting\":0,\"sysOrgCode\":\"A03A01A07\",\"remarks\":\" 华亭\"}],\"timestamp\":1724893995712}";
        log.info("Response content: " + output);
        ObjectMapper mapper = new ObjectMapper();

        try {
            Map<String, Object> responseMap = mapper.readValue(output, Map.class);
            List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
            groupStatisticMapper.deleteAssessment();
            for (Map<String, Object> recordMap : resultList) {
                EnvironmentRanking assessment = mapper.convertValue(recordMap, EnvironmentRanking.class);

                groupStatisticMapper.insertAssessment(assessment);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to process the data", e); // Ensure the transaction is rolled back
        }
        return 0;
    }

    @Transactional
    @Override
    public int getEfficientTransmission() throws Exception {
        String url = "http://10.244.131.192:9000/chartInterface/getEffectiveRate_4?date=2024-6";
        String output = sendGet(url);
        log.info("Response content: " + output);
        ObjectMapper mapper = new ObjectMapper();

        try {
            Map<String, Object> responseMap = mapper.readValue(output, Map.class);
            List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
            groupStatisticMapper.deleteEfficientTransmission();
            for (Map<String, Object> recordMap : resultList) {
                EfficientTransmission assessment = mapper.convertValue(recordMap, EfficientTransmission.class);

                groupStatisticMapper.insertEfficientTransmission(assessment);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to process the data", e); // Ensure the transaction is rolled back
        }
        return 0;
    }

    @Override
    public List<ExecutionCostVO> selectExecutionCostTotalByCompanyCodeOrName(ExecutionCostReq planMining) {
        List<ExecutionCostVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            ExecutionCostVO planMiningVO = costMapper.selectExecutionCostTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<ExecutionWashingVO> selectExecutionWashingTotalByCompanyCodeOrName(ExecutionWashingReq planMining) {
        List<ExecutionWashingVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            ExecutionWashingVO planMiningVO = washingMapper.selectExecutionWashingTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }

            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());
            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<PlanDrivageVO> selectDrivageTotalByCompanyCodeOrName(PlanDrivageReq planMining) {
        List<PlanDrivageVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            PlanDrivageVO planMiningVO = planDrivageMapper.selectDrivageTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }

            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<PlanWashingVO> selectWashingTotalByCompanyCodeOrName(PlanWashingReq planMining) {
        List<PlanWashingVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            PlanWashingVO planMiningVO = planWashingMapper.selectDrivageTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<PlanOtherVO> selectOtherTotalByCompanyCodeOrName(PlanOtherReq planMining) {
        List<PlanOtherVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            PlanOtherVO planMiningVO = planOtherMapper.selectDrivageTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<DimMiningFaceVO> selectDimMiningFaceTotalByCompanyCodeOrName(DimMiningFaceReq planMining) {
        List<DimMiningFaceVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        DynamicDataSourceContextHolder.push("slave");
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            DimMiningFaceVO planMiningVO = dimMiningFaceMapper.selectDrivageTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        DynamicDataSourceContextHolder.clear();
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;

        //先查询所有的
        //查完所有再查每个公司的
        //在查每个矿的


    }

    @Override
    public List<DimDrivageFaceVO> selectDimDrivageFaceTotalByCompanyCodeOrName(DimDrivageFaceReq planMining) {
        List<DimDrivageFaceVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        DynamicDataSourceContextHolder.push("slave");
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            DimDrivageFaceVO planMiningVO = dimDrivageFaceMapper.selectDimDrivageFaceTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        DynamicDataSourceContextHolder.clear();
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<PlanOutputVO> selectPlanOutputTotalByCompanyCodeOrName(PlanOutputReq planMining) {
        List<PlanOutputVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            PlanOutputVO planMiningVO = planOutputMapper.selectDimDrivageFaceTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<ExecutionFootageOutputVO> selectFootageOutputTotalByCompanyCodeOrName(ExecutionFootageOutputReq planMining) {
        List<ExecutionFootageOutputVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            ExecutionFootageOutputVO planMiningVO = footageOutputMapper.selectDimDrivageFaceTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<ExecutionOtherVO> selectExecutionOtherTotalByCompanyCodeOrName(ExecutionOtherReq planMining) {
        List<ExecutionOtherVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            ExecutionOtherVO planMiningVO = otherMapper.selectExecutionOtherTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<PlanMiningVO> selectMiningTotalByCompanyCodeOrName(PlanMiningReq planMining) {
        List<PlanMiningVO> planMiningVOS = new ArrayList<>();
        Map<String, MineBaseConstants.Mine> nameByCompanyCodeOfMap = MineBaseConstants.getNameByCompanyCodeOfMap(
                planMining.getCompanyCode(), planMining.getCompanyName());
//        System.out.println(nameByCompanyCodeOfMap);
        for (String key : nameByCompanyCodeOfMap.keySet()) {
            System.out.println(key);
            PlanMiningVO planMiningVO = planMiningMapper.selectExecutionOtherTotalByCompanyCodeOrName(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            if (planMiningVO == null) {
                continue;
            }
            if (planMiningVO.getTotalPlan().equals("0")) {
                continue;
            }
            planMiningVO.setCompanyCode(nameByCompanyCodeOfMap.get(key).getCompanyCode());
            planMiningVO.setCompanyName(nameByCompanyCodeOfMap.get(key).getCompanyName());

            planMiningVOS.add(planMiningVO);
        }
        nameByCompanyCodeOfMap.clear();
        return planMiningVOS;
    }

    @Override
    public List<Tree<Integer>> selectDimMiningFaceName(DimMiningFaceReq planMining) {
        //调用接口
        List<Tree<Integer>> treeSelectOrg = remoteDeptService.getTreeSelectOrg(new SysDept());
        return treeSelectOrg;
    }


    @Override
    public CockpitSaleVo getGroupYield(SaleAnalyseReq req) {
        LocalTime currentTime = LocalTime.now();
        Integer flag = null;
        SaleAnalyseVo prvAnalyseVoMonth = new SaleAnalyseVo();
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
            System.out.println("当前时间在0点和10点之间");
            flag = 1;
            prvAnalyseVoMonth = groupStatisticMapper.prvSaleAnalyseTen(null);

        } else {
            System.out.println("当前时间不在0点和10点之间");
            prvAnalyseVoMonth = groupStatisticMapper.prvSaleAnalyse(null);

        }
        SaleAnalyseVo saleAnalyseVo = groupStatisticService.saleAnalyse(req);

        CockpitSaleVo v = new CockpitSaleVo();
        v.setYearSale(saleAnalyseVo.getYearSale().setScale(0, BigDecimal.ROUND_HALF_UP));
        v.setYearPlanSale(saleAnalyseVo.getYearPlan().setScale(0, BigDecimal.ROUND_HALF_UP));
        v.setMonthSale(saleAnalyseVo.getSale().setScale(0, BigDecimal.ROUND_HALF_UP));
        v.setMonthPlanSale(saleAnalyseVo.getPlan().setScale(0, BigDecimal.ROUND_HALF_UP));

        v.setMonthPlanFinishingRate(saleAnalyseVo.getMonthCount().intValue());
        v.setYearPlanFinishingRate(saleAnalyseVo.getYearCount().intValue());
        // 昨日销量
        v.setPrvSale(prvAnalyseVoMonth == null ? new BigDecimal(0) : prvAnalyseVoMonth.getPrvSale().setScale(0, BigDecimal.ROUND_HALF_UP));
        Calendar calendar = Calendar.getInstance();
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        v.setPrvPlanSale(v.getMonthPlanSale().divide(new BigDecimal(days), 0, BigDecimal.ROUND_HALF_UP));
        v.setPrvPlanFinishingRate(v.getPrvPlanSale() == null || v.getPrvPlanSale().compareTo(BigDecimal.valueOf(0)) == 0 ? 0 : v.getPrvSale().divide(v.getPrvPlanSale(), 0, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).intValue());
        return v;
    }

    public static void main(String[] args) {
        BigDecimal a = new BigDecimal(247272.1);
        BigDecimal b = new BigDecimal(289655);
        System.out.println(a.divide(b, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
        BigDecimal c = new BigDecimal(12.51);
        System.out.println(c.intValue());
    }

    static final String[] MY = CoalInfo.getCompanyCodesByCompanyType("0");
    static final String[] BF = CoalInfo.getCompanyCodesByCompanyType("1");
    static final String[] MD = CoalInfo.getCompanyCodesByCompanyType("2");

    static final String[] ZJ = CoalInfo.getCompanyCodes().toArray(new String[0]);

    static final List<String> order = Arrays.asList("总计", "华亭煤业", "扎煤公司", "陕西矿业", "庆阳煤电", "滇东公司");
    static final List<String> coalOrder = Arrays.asList("华亭煤矿", "砚北煤矿", "陈家沟煤矿", "东峡煤矿", "山寨煤矿", "新窑煤矿", "新柏煤矿", "大柳煤矿", "赤城煤矿", "灵泉煤矿", "铁北煤矿", "灵东煤矿", "灵露煤矿", "西川煤矿", "青岗坪煤矿", "柳巷煤矿", "核桃峪煤矿", "新庄煤矿", "白龙山一井", "雨汪一井", "魏家峁露天矿", "高头窑煤矿", "铧尖露天矿", "伊敏露天矿");


    @Override
    public List<CockpitSaleVo> planVersusPractice(SaleAnalyseReq req) {
        List<CockpitSaleVo> list = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Calendar tenAM = Calendar.getInstance();
        tenAM.set(Calendar.HOUR_OF_DAY, 10);
        tenAM.set(Calendar.MINUTE, 0);
        tenAM.set(Calendar.SECOND, 0);
        tenAM.set(Calendar.MILLISECOND, 0);
        int timeflag = 10;
        // 判断当前时间是否超过上午10点
        if (new Date().before(tenAM.getTime())) {
            // 如果当前时间未超过上午10点，则将时间减去一天
            timeflag = 9;
        }
        switch (req.getDateType()) {
            case "0"://日   煤炭产业 煤业公司 煤矿
                switch (req.getDataType()) {
//                    查询数据类型:0煤炭产业1煤业公司2煤矿
                    case "0"://日 煤炭产业
                        CockpitSaleVo my = new CockpitSaleVo("煤业公司");
                        CockpitSaleVo bf = new CockpitSaleVo("北方公司");
                        CockpitSaleVo md = new CockpitSaleVo("蒙东公司");
                        CockpitSaleVo zj = new CockpitSaleVo("总计");
                        SaleAnalyseVo prvMy = new SaleAnalyseVo();
                        SaleAnalyseVo prvBf = new SaleAnalyseVo();
                        SaleAnalyseVo prvMd = new SaleAnalyseVo();
                        SaleAnalyseVo prvZj = new SaleAnalyseVo();
                        if (timeflag == 9) {
                            prvMy = groupStatisticMapper.prvSaleAnalyseTwo(MY);
                            prvBf = groupStatisticMapper.prvSaleAnalyseTwo(BF);
                            prvMd = groupStatisticMapper.prvSaleAnalyseTwo(MD);
                            prvZj = groupStatisticMapper.prvSaleAnalyseTwo(ZJ);
                        } else {
                            prvMy = groupStatisticMapper.prvSaleAnalyse(MY);
                            prvBf = groupStatisticMapper.prvSaleAnalyse(BF);
                            prvMd = groupStatisticMapper.prvSaleAnalyse(MD);
                            prvZj = groupStatisticMapper.prvSaleAnalyse(ZJ);
                        }


                        SaleAnalyseVo monthMy = groupStatisticMapper.monthSaleAnalyse(MY);
                        SaleAnalyseVo monthBf = groupStatisticMapper.monthSaleAnalyse(BF);
                        SaleAnalyseVo monthMd = groupStatisticMapper.monthSaleAnalyse(MD);
                        SaleAnalyseVo monthZj = groupStatisticMapper.monthSaleAnalyse(ZJ);

                        my.setPrvPlanSale(monthMy.getPlan().divide(new BigDecimal(days), 2, BigDecimal.ROUND_DOWN));
                        my.setPrvSale(prvMy.getPrvSale());

                        bf.setPrvPlanSale(monthBf.getPlan().divide(new BigDecimal(days), 2, BigDecimal.ROUND_DOWN));
                        bf.setPrvSale(prvBf.getPrvSale());

                        md.setPrvPlanSale(monthMd.getPlan().divide(new BigDecimal(days), 2, BigDecimal.ROUND_DOWN));
                        md.setPrvSale(prvMd.getPrvSale());

                        zj.setPrvPlanSale(monthZj.getPlan().divide(new BigDecimal(days), 2, BigDecimal.ROUND_DOWN));
                        zj.setPrvSale(prvZj.getPrvSale());

                        my.setExceedOwe(my.getPrvSale().subtract(my.getPrvPlanSale()));
                        bf.setExceedOwe(bf.getPrvSale().subtract(bf.getPrvPlanSale()));
                        md.setExceedOwe(md.getPrvSale().subtract(md.getPrvPlanSale()));
                        zj.setExceedOwe(zj.getPrvSale().subtract(zj.getPrvPlanSale()));
                        list.add(my);
                        list.add(bf);
                        list.add(md);
//                        list.add(zj);
                        return list;
                    case "1"://日  煤业公司
                        List<SaleAnalyseVo> prvMygslist = new ArrayList<>();
                        if (timeflag == 9) {
                            prvMygslist = groupStatisticMapper.prvSaleAnalyseMyAndMkTwo(MY, null);

                        } else {
                            prvMygslist = groupStatisticMapper.prvSaleAnalyseMyAndMk(MY, null);

                        }
                        List<SaleAnalyseVo> monthMyglist = groupStatisticMapper.monthSaleAnalyseMyAndMk(MY, null);

                        for (int i = 0; i < prvMygslist.size(); i++) {
                            SaleAnalyseVo saleAnalyseVo = prvMygslist.get(i);
                            //todo 昨日计划销量最后赋值给需要返回的list里面
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setCompanyCode(saleAnalyseVo.getCompanyCode());
                            v.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(saleAnalyseVo.getCompanyCode()).replace("公司", "").replace("煤业", "").replace("矿业", "").replace("煤电", ""));
                            for (int j = 0; j < monthMyglist.size(); j++) {
                                if (monthMyglist.get(j).getCompanyCode().equals(saleAnalyseVo.getCompanyCode())) {
                                    v.setPrvPlanSale(monthMyglist.get(j).getPlan().divide(new BigDecimal(days), 2, BigDecimal.ROUND_DOWN));
                                }
                            }
                            v.setPrvSale(saleAnalyseVo.getPrvSale());
                            v.setExceedOwe(v.getPrvSale().subtract(v.getPrvPlanSale()));
                            list.add(v);
                        }

                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<CockpitSaleVo> sortedList = list.stream()
                                .filter(vo -> !vo.getCompanyName().equals("滇东"))
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

//                        BigDecimal totalPrvPlanSale = new BigDecimal(0);
//                        BigDecimal totalPrvSale = new BigDecimal(0);

//                        // 遍历列表累加
//                        for (CockpitSaleVo item : sortedList) {
//                            totalPrvPlanSale = totalPrvPlanSale.add(item.getPrvPlanSale());
//                            totalPrvSale = totalPrvSale.add(item.getPrvSale());
//                        }
//
//                        CockpitSaleVo cockpitSaleVo = new CockpitSaleVo();
//                        cockpitSaleVo.setCompanyName("总计");
//                        cockpitSaleVo.setPrvPlanSale(totalPrvPlanSale);
//                        cockpitSaleVo.setPrvSale(totalPrvSale);
//                        cockpitSaleVo.setExceedOwe(totalPrvSale.subtract(totalPrvPlanSale));
//                        sortedList.add(cockpitSaleVo);

                        return sortedList;
                    case "2"://日 矿
                        List<SaleAnalyseVo> prvCoallist = new ArrayList<>();
                        if (timeflag == 9) {
                            prvCoallist = groupStatisticMapper.prvSaleAnalyseMyAndMkTwo(null, "coal");

                        } else {
                            prvCoallist = groupStatisticMapper.prvSaleAnalyseMyAndMk(null, "coal");
                        }
                        List<SaleAnalyseVo> monthCoalList = groupStatisticMapper.monthSaleAnalyseMyAndMk(null, "coal");

                        for (SaleAnalyseVo saleAnalyseVo : prvCoallist) {
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setMineCode(saleAnalyseVo.getMineCode());
                            v.setMineName(CoalInfo.getMineNameByMineCode(saleAnalyseVo.getMineCode()));
                            v.setMineName(v.getMineName().replace("公司", "煤矿").replace("铁北矿", "铁北煤矿"));
                            for (SaleAnalyseVo monthList : monthCoalList) {
                                if (monthList.getMineCode().equals(saleAnalyseVo.getMineCode())) {
                                    v.setPrvPlanSale(monthList.getPlan().divide(BigDecimal.valueOf(days), 2, BigDecimal.ROUND_DOWN));
                                }
                            }
                            v.setPrvSale(saleAnalyseVo.getPrvSale());
                            v.setExceedOwe(v.getPrvSale().subtract(v.getPrvPlanSale()));
                            list.add(v);
                        }

                        // 创建一个映射，用于将mineName映射到其在order中的索引
                        Map<String, Integer> coalMap = new HashMap<>();
                        for (int i = 0; i < coalOrder.size(); i++) {
                            coalMap.put(coalOrder.get(i), i);
                        }

                        // 根据定义的顺序对list进行排序
                        list = list.stream()
                                .filter(vo -> !vo.getMineName().equals("马蹄沟煤矿"))
                                .filter(vo -> !vo.getMineName().equals("新庄煤矿"))
                                .filter(vo -> !vo.getMineName().equals("刘园子煤矿"))
                                .filter(vo -> !vo.getMineName().equals("白龙山煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals("雨汪煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals(" "))
                                .map(vo -> {
                                    if (vo.getMineName().equals("铁北矿")) {
                                        vo.setMineName("铁北煤矿");
                                    }
                                    if (vo.getMineName().equals("灵东矿")) {
                                        vo.setMineName("灵东煤矿");
                                    }
                                    if (vo.getMineName().equals("灵泉矿")) {
                                        vo.setMineName("灵泉煤矿");
                                    }
                                    if (vo.getMineName().equals("灵露矿")) {
                                        vo.setMineName("灵露煤矿");
                                    }
//                                    if (vo.getMineName().equals("白龙山煤矿一井")) {
//                                        vo.setMineName("白龙山一井");
//                                    }
//                                    if (vo.getMineName().equals("雨汪煤矿一井")) {
//                                        vo.setMineName("雨汪一井");
//                                    }
                                    return vo;
                                })
                                .sorted(Comparator.comparingInt(vo -> coalMap.getOrDefault(vo.getMineName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());
                        if (StringUtils.isNotEmpty(req.getCompanyCode())) {
                            if (req.getCompanyCode().equalsIgnoreCase("91150781720169744B")) {
                                list.removeIf(v -> !v.getCompanyCode().equalsIgnoreCase("91150781720169744B"));
                            }
                        }
                        return list;
                }

            case "1"://月
                switch (req.getDataType()) {
                    case "0"://月 煤炭产业
                        CockpitSaleVo my = new CockpitSaleVo("煤业公司");
                        CockpitSaleVo bf = new CockpitSaleVo("北方公司");
                        CockpitSaleVo md = new CockpitSaleVo("蒙东公司");
                        CockpitSaleVo zj = new CockpitSaleVo("总计");
                        SaleAnalyseVo monthMy = groupStatisticMapper.monthSaleAnalyse(MY);
                        SaleAnalyseVo monthBf = groupStatisticMapper.monthSaleAnalyse(BF);
                        SaleAnalyseVo monthMd = groupStatisticMapper.monthSaleAnalyse(MD);
                        SaleAnalyseVo monthZj = groupStatisticMapper.monthSaleAnalyse(ZJ);
                        my.setMonthPlanSale(monthMy.getPlan());
                        my.setMonthSale(monthMy.getSale());
                        bf.setMonthPlanSale(monthBf.getPlan());
                        bf.setMonthSale(monthBf.getSale());
                        md.setMonthPlanSale(monthMd.getPlan());
                        md.setMonthSale(monthMd.getSale());

                        zj.setMonthPlanSale(monthZj.getPlan());
                        zj.setMonthSale(monthZj.getSale());

                        my.setExceedOwe(my.getMonthSale().subtract(my.getMonthPlanSale()));
                        bf.setExceedOwe(bf.getMonthSale().subtract(bf.getMonthPlanSale()));
                        md.setExceedOwe(md.getMonthSale().subtract(md.getMonthPlanSale()));
                        zj.setExceedOwe(zj.getMonthSale().subtract(zj.getMonthPlanSale()));

                        list.add(my);
                        list.add(bf);
                        list.add(md);
//                        list.add(zj);
                        return list;
                    case "1"://月 煤业公司
                        List<SaleAnalyseVo> monthMyList = groupStatisticMapper.monthSaleAnalyseMyAndMk(MY, null);
                        for (SaleAnalyseVo mml : monthMyList) {
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setMonthPlanSale(mml.getPlan());
                            v.setMonthSale(mml.getSale());
                            v.setExceedOwe(mml.getSale().subtract(mml.getPlan()));
                            v.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mml.getCompanyCode()).replace("公司", "").replace("煤业", "").replace("矿业", "").replace("煤电", ""));
                            v.setCompanyCode(mml.getCompanyCode());
                            list.add(v);
                        }

                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<CockpitSaleVo> sortedList = list.stream()
                                .filter(vo -> !vo.getCompanyName().equals("滇东"))
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

//                        BigDecimal totalMonthPlanSale = new BigDecimal(0);
//                        BigDecimal totalMonthSale = new BigDecimal(0);
//
//                        // 遍历列表累加
//                        for (CockpitSaleVo item : sortedList) {
//                            totalMonthPlanSale = totalMonthPlanSale.add(item.getMonthPlanSale());
//                            totalMonthSale = totalMonthSale.add(item.getMonthSale());
//                        }
//
//                        CockpitSaleVo cockpitSaleVo = new CockpitSaleVo();
//                        cockpitSaleVo.setCompanyName("总计");
//                        cockpitSaleVo.setMonthPlanSale(totalMonthPlanSale);
//                        cockpitSaleVo.setMonthSale(totalMonthSale);
//                        cockpitSaleVo.setExceedOwe(totalMonthSale.subtract(totalMonthPlanSale));
//                        sortedList.add(cockpitSaleVo);

                        return sortedList;
                    case "2"://月 矿
                        List<SaleAnalyseVo> monthCoalList = groupStatisticMapper.monthSaleAnalyseMyAndMk(null, "coal");
                        for (SaleAnalyseVo mcl : monthCoalList) {
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setMonthPlanSale(mcl.getPlan());
                            v.setMonthSale(mcl.getSale());
                            v.setExceedOwe(mcl.getSale().subtract(mcl.getPlan()));
                            v.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mcl.getCompanyCode()));
                            v.setCompanyCode(mcl.getCompanyCode());
                            v.setMineName(CoalInfo.getMineNameByMineCode(mcl.getMineCode()));
                            v.setMineName(v.getMineName().replace("公司", "煤矿"));
//                            v.setMineName(CoalInfo.getMineNameByMineCode(mcl.getMineCode()).replace("公司",""));
                            v.setMineCode(mcl.getMineCode());
                            list.add(v);
                        }
                        Map<String, Integer> coalMap = new HashMap<>();
                        for (int i = 0; i < coalOrder.size(); i++) {
                            coalMap.put(coalOrder.get(i), i);
                        }

                        // 根据定义的顺序对list进行排序
                        list = list.stream()
                                .filter(vo -> !vo.getMineName().equals("马蹄沟煤矿"))
                                .filter(vo -> !vo.getMineName().equals("新庄煤矿"))
                                .filter(vo -> !vo.getMineName().equals("刘园子煤矿"))
                                .filter(vo -> !vo.getMineName().equals("白龙山煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals("雨汪煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals(" "))
                                .map(vo -> {
                                    if (vo.getMineName().equals("铁北矿")) {
                                        vo.setMineName("铁北煤矿");
                                    }
                                    if (vo.getMineName().equals("灵东矿")) {
                                        vo.setMineName("灵东煤矿");
                                    }
                                    if (vo.getMineName().equals("灵泉矿")) {
                                        vo.setMineName("灵泉煤矿");
                                    }
                                    if (vo.getMineName().equals("灵露矿")) {
                                        vo.setMineName("灵露煤矿");
                                    }
//                                    if (vo.getMineName().equals("白龙山煤矿一井")) {
//                                        vo.setMineName("白龙山一井");
//                                    }
//                                    if (vo.getMineName().equals("雨汪煤矿一井")) {
//                                        vo.setMineName("雨汪一井");
//                                    }
                                    return vo;
                                })
                                .sorted(Comparator.comparingInt(vo -> coalMap.getOrDefault(vo.getMineName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());
                        if(StringUtils.isNotEmpty(req.getCompanyCode())){
                            if (req.getCompanyCode().equalsIgnoreCase("91150781720169744B")) {
                                list.removeIf(v -> !v.getCompanyCode().equalsIgnoreCase("91150781720169744B"));
                            }
                        }
                        return list;
                }


            case "2"://年

                switch (req.getDataType()) {
                    case "0":
                        CockpitSaleVo my = new CockpitSaleVo("煤业公司");
                        CockpitSaleVo bf = new CockpitSaleVo("北方公司");
                        CockpitSaleVo md = new CockpitSaleVo("蒙东公司");
                        CockpitSaleVo zj = new CockpitSaleVo("总计");
                        SaleAnalyseVo yearMy = groupStatisticMapper.yearSaleAnalyse(MY);
                        SaleAnalyseVo yearBf = groupStatisticMapper.yearSaleAnalyse(BF);
                        SaleAnalyseVo yearMd = groupStatisticMapper.yearSaleAnalyse(MD);
                        SaleAnalyseVo yearZj = groupStatisticMapper.yearSaleAnalyse(ZJ);

                        my.setYearPlanSale(yearMy.getPlan());
                        my.setYearSale(yearMy.getSale());

                        bf.setYearPlanSale(yearBf.getPlan());
                        bf.setYearSale(yearBf.getSale());

                        md.setYearPlanSale(yearMd.getPlan());
                        md.setYearSale(yearMd.getSale());

                        zj.setYearPlanSale(yearZj.getPlan());
                        zj.setYearSale(yearZj.getSale());

                        my.setExceedOwe(my.getYearSale().subtract(my.getYearPlanSale()));
                        bf.setExceedOwe(bf.getYearSale().subtract(bf.getYearPlanSale()));
                        md.setExceedOwe(md.getYearSale().subtract(md.getYearPlanSale()));
                        zj.setExceedOwe(zj.getYearSale().subtract(zj.getYearPlanSale()));

                        list.add(my);
                        list.add(bf);
                        list.add(md);
//                        list.add(zj);
                        return list;
                    case "1":
                        List<SaleAnalyseVo> yearMyList = groupStatisticMapper.yearSaleAnalyseMyAndMk(MY, null);
                        for (SaleAnalyseVo yml : yearMyList) {
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setYearPlanSale(yml.getYearPlan());
                            v.setYearSale(yml.getYearSale());
                            v.setExceedOwe(yml.getYearSale().subtract(yml.getYearPlan()));
                            v.setCompanyCode(yml.getCompanyCode());
                            v.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(yml.getCompanyCode()).replace("公司", "").replace("煤业", "").replace("矿业", "").replace("煤电", ""));
                            list.add(v);
                        }
                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<CockpitSaleVo> sortedList = list.stream()
                                .filter(vo -> !vo.getCompanyName().equals("滇东"))
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

//                        BigDecimal totalYearPlanSale = new BigDecimal(0);
//                        BigDecimal totalYearSale = new BigDecimal(0);
//
//                        // 遍历列表累加
//                        for (CockpitSaleVo item : sortedList) {
//                            totalYearPlanSale = totalYearPlanSale.add(item.getYearPlanSale());
//                            totalYearSale = totalYearSale.add(item.getYearSale());
//                        }
//
//                        CockpitSaleVo cockpitSaleVo = new CockpitSaleVo();
//                        cockpitSaleVo.setCompanyName("总计");
//                        cockpitSaleVo.setYearPlanSale(totalYearPlanSale);
//                        cockpitSaleVo.setYearSale(totalYearSale);
//                        cockpitSaleVo.setExceedOwe(totalYearSale.subtract(totalYearPlanSale));
//                        sortedList.add(cockpitSaleVo);
                        return sortedList;
                    case "2":
                        List<SaleAnalyseVo> yearMkList = groupStatisticMapper.yearSaleAnalyseMyAndMk(null, "coal");
                        for (SaleAnalyseVo mk : yearMkList) {
                            CockpitSaleVo v = new CockpitSaleVo();
                            v.setYearPlanSale(mk.getYearPlan());
                            v.setYearSale(mk.getYearSale());
                            v.setExceedOwe(mk.getYearSale().subtract(mk.getYearPlan()));
                            v.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mk.getCompanyCode()));
                            v.setCompanyCode(mk.getCompanyCode());
//                            v.setMineName(CoalInfo.getMineNameByMineCode(mk.getMineCode()).replace("公司",""));
                            v.setMineName(CoalInfo.getMineNameByMineCode(mk.getMineCode()));
                            v.setMineName(v.getMineName().replace("公司", "煤矿"));
                            v.setMineCode(mk.getMineCode());
                            list.add(v);
                        }
                        Map<String, Integer> coalMap = new HashMap<>();
                        for (int i = 0; i < coalOrder.size(); i++) {
                            coalMap.put(coalOrder.get(i), i);
                        }

                        // 根据定义的顺序对list进行排序
                        list = list.stream()
                                .filter(vo -> !vo.getMineName().equals("马蹄沟煤矿"))
                                .filter(vo -> !vo.getMineName().equals("新庄煤矿"))
                                .filter(vo -> !vo.getMineName().equals("刘园子煤矿"))
                                .filter(vo -> !vo.getMineName().equals("白龙山煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals("雨汪煤矿一井"))
                                .filter(vo -> !vo.getMineName().equals(" "))
                                .map(vo -> {
                                    if (vo.getMineName().equals("铁北矿")) {
                                        vo.setMineName("铁北煤矿");
                                    }
                                    if (vo.getMineName().equals("灵东矿")) {
                                        vo.setMineName("灵东煤矿");
                                    }
                                    if (vo.getMineName().equals("灵泉矿")) {
                                        vo.setMineName("灵泉煤矿");
                                    }
                                    if (vo.getMineName().equals("灵露矿")) {
                                        vo.setMineName("灵露煤矿");
                                    }
//                                    if (vo.getMineName().equals("白龙山煤矿一井")) {
//                                        vo.setMineName("白龙山一井");
//                                    }
//                                    if (vo.getMineName().equals("雨汪煤矿一井")) {
//                                        vo.setMineName("雨汪一井");
//                                    }
                                    return vo;
                                })
                                .sorted(Comparator.comparingInt(vo -> coalMap.getOrDefault(vo.getMineName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

                        if(StringUtils.isNotEmpty(req.getCompanyCode())){
                            if (req.getCompanyCode().equalsIgnoreCase("91150781720169744B")) {
                                list.removeIf(v -> !v.getCompanyCode().equalsIgnoreCase("91150781720169744B"));
                            }
                        }

                        return list;
                }
        }
        return null;
    }

    public List<SaleAnalyseVo> setListCompanyName(List<SaleAnalyseVo> l, String companyName) {

        for (SaleAnalyseVo t : l) {
            t.setCompanyName(companyName);
        }

        return l;
    }

    @Override
    public List<SaleAnalyseVo> variationTrend(SaleAnalyseReq req) {
        List<SaleAnalyseVo> list = new ArrayList<>();
        Map<String, List<SaleAnalyseVo>> map = new HashMap<>();
        // 获取当前时间
        LocalTime currentTime = LocalTime.now();
        switch (req.getDateType()) {
            case "0"://近30日
                switch (req.getDataType()) {
                    case "0":// 近30日 煤炭产业

                        List<SaleAnalyseVo> myList = new ArrayList<>();
                        List<SaleAnalyseVo> bfList = new ArrayList<>();
                        List<SaleAnalyseVo> mdList = new ArrayList<>();
                        List<SaleAnalyseVo> zjList = new ArrayList<>();
                        // 检查当前时间是否在0点到10点之间
                        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
                            // 在0点到10点之间，执行查询操作
                            myList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(MY, null);
                            bfList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(BF, null);
                            mdList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(MD, null);
                            zjList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(ZJ, null);
                        } else {
                            // 不在0点到10点之间，执行另一个操作
                            myList = groupStatisticMapper.last30DaysVariationTrend(MY, null);
                            bfList = groupStatisticMapper.last30DaysVariationTrend(BF, null);
                            mdList = groupStatisticMapper.last30DaysVariationTrend(MD, null);
                            zjList = groupStatisticMapper.last30DaysVariationTrend(ZJ, null);
                        }
//                        List<SaleAnalyseVo> myList = groupStatisticMapper.last30DaysVariationTrend(MY, null);
//                        List<SaleAnalyseVo> bfList = groupStatisticMapper.last30DaysVariationTrend(BF, null);
//                        List<SaleAnalyseVo> mdList = groupStatisticMapper.last30DaysVariationTrend(MD, null);
//                        List<SaleAnalyseVo> zjList = groupStatisticMapper.last30DaysVariationTrend(ZJ, null);

                        myList = setListCompanyName(myList, "煤业公司");
                        bfList = setListCompanyName(bfList, "北方公司");
                        mdList = setListCompanyName(mdList, "蒙东公司");
                        zjList = setListCompanyName(zjList, "总计");

                        List<SaleAnalyseVo> last30Days = Stream.concat(Stream.concat(Stream.concat(myList.stream(), bfList.stream()), mdList.stream()), zjList.stream())
                                .collect(Collectors.toList());

                        return last30Days;
                    case "1":// 近30日 煤业公司
                        List<SaleAnalyseVo> mygsCountList = new ArrayList<>();
                        List<SaleAnalyseVo> mygsList = new ArrayList<>();
                        // 检查当前时间是否在0点到10点之间
                        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
                            // 在0点到10点之间，执行查询操作
                            mygsCountList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(MY, null);
                            mygsList = groupStatisticMapper.last30DaysVariationTrendBeforeYesterday(MY, "my");
                        } else {
                            // 不在0点到10点之间，执行另一个操作
                            mygsCountList = groupStatisticMapper.last30DaysVariationTrend(MY, null);
                            mygsList = groupStatisticMapper.last30DaysVariationTrend(MY, "my");
                        }
//                        List<SaleAnalyseVo> mygsCountList = groupStatisticMapper.last30DaysVariationTrend(MY, null);
//                        List<SaleAnalyseVo> mygsList = groupStatisticMapper.last30DaysVariationTrend(MY, "my");
                        mygsCountList = setListCompanyName(mygsCountList, "总计");
                        List<SaleAnalyseVo> last30List = Stream.concat(mygsCountList.stream(), mygsList.stream())
                                .collect(Collectors.toList());
                        for (SaleAnalyseVo mygs : last30List) {
                            if (StrUtil.isNotBlank(mygs.getCompanyCode())) {
                                mygs.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mygs.getCompanyCode()).replace("公司", "").replace("煤业", "").replace("矿业", "").replace("煤电", ""));
                            }
                        }

                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<SaleAnalyseVo> sortedList = last30List.stream()
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

                        return sortedList;
                }
            case "1"://近12月
                switch (req.getDataType()) {
                    case "0":// 近12月 煤炭产业
                        List<SaleAnalyseVo> myList = groupStatisticMapper.last12MonthsVariationTrend(MY, null);
                        List<SaleAnalyseVo> bfList = groupStatisticMapper.last12MonthsVariationTrend(BF, null);
                        List<SaleAnalyseVo> mdList = groupStatisticMapper.last12MonthsVariationTrend(MD, null);
                        List<SaleAnalyseVo> zjList = groupStatisticMapper.last12MonthsVariationTrend(ZJ, null);
                        myList = setListCompanyName(myList, "煤业公司");
                        bfList = setListCompanyName(bfList, "北方公司");
                        mdList = setListCompanyName(mdList, "蒙东公司");
                        zjList = setListCompanyName(zjList, "总计");
                        List<SaleAnalyseVo> mergedList = Stream.concat(Stream.concat(Stream.concat(myList.stream(), bfList.stream()), mdList.stream()), zjList.stream())
                                .collect(Collectors.toList());

                        return mergedList;
                    case "1":// 近12月 煤业公司
                        List<SaleAnalyseVo> mygsCountList = groupStatisticMapper.last12MonthsVariationTrend(MY, null);
                        mygsCountList = setListCompanyName(mygsCountList, "总计");

                        List<SaleAnalyseVo> mygsList = groupStatisticMapper.last12MonthsVariationTrend(MY, "my");
                        List<SaleAnalyseVo> last12Month = Stream.concat(mygsCountList.stream(), mygsList.stream())
                                .collect(Collectors.toList());
                        for (SaleAnalyseVo mygs : last12Month) {
                            if (StrUtil.isNotBlank(mygs.getCompanyCode())) {
                                mygs.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mygs.getCompanyCode()).replace("公司", "").replace("煤业", "").replace("矿业", "").replace("煤电", ""));
                            }
                        }
                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<SaleAnalyseVo> sortedList = last12Month.stream()
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

                        return sortedList;
                }
            case "2"://近10年
                switch (req.getDataType()) {
                    case "0":// 近10年 煤炭产业
                        List<SaleAnalyseVo> myList = groupStatisticMapper.last10YearsVariationTrend(MY, null);
                        List<SaleAnalyseVo> bfList = groupStatisticMapper.last10YearsVariationTrend(BF, null);
                        List<SaleAnalyseVo> mdList = groupStatisticMapper.last10YearsVariationTrend(MD, null);
                        List<SaleAnalyseVo> zjList = groupStatisticMapper.last10YearsVariationTrend(ZJ, null);
                        myList = setListCompanyName(myList, "煤业公司");
                        bfList = setListCompanyName(bfList, "北方公司");
                        mdList = setListCompanyName(mdList, "蒙东公司");
                        zjList = setListCompanyName(zjList, "总计");
                        List<SaleAnalyseVo> mergedList = Stream.concat(Stream.concat(Stream.concat(myList.stream(), bfList.stream()), mdList.stream()), zjList.stream())
                                .collect(Collectors.toList());
                        return mergedList;
                    case "1":// 近10年 煤业公司
                        List<SaleAnalyseVo> mygsCountList = groupStatisticMapper.last10YearsVariationTrend(MY, null);
                        mygsCountList = setListCompanyName(mygsCountList, "总计");

                        List<SaleAnalyseVo> mygsList = groupStatisticMapper.last10YearsVariationTrend(MY, "my");

                        List<SaleAnalyseVo> last10YearList = Stream.concat(mygsCountList.stream(), mygsList.stream())
                                .collect(Collectors.toList());

                        for (SaleAnalyseVo mygs : last10YearList) {
                            if (StrUtil.isNotBlank(mygs.getCompanyCode())) {
                                mygs.setCompanyName(CoalInfo.getCompanyReferredByCompanyCode(mygs.getCompanyCode()).replace("", "").replace("", "").replace("", "").replace("", ""));
                            }
                        }


                        Map<String, Integer> indexMap = new HashMap<>();
                        for (int i = 0; i < order.size(); i++) {
                            indexMap.put(order.get(i), i);
                        }

                        List<SaleAnalyseVo> sortedList = last10YearList.stream()
                                .filter(vo -> !vo.getCompanyName().equals("滇东公司"))
                                .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                                .collect(Collectors.toList());

                        return sortedList;
                }
        }
        return null;
    }

    @Override
    public Map<String, List<repertoryInfo>> inventory() {
        Map<String, List<repertoryInfo>> map = new HashMap<>();
        List<repertoryInfo> listInfo = groupStatisticMapper.inventoryInfo();
        for (repertoryInfo info : listInfo) {
            info.setCoalStorage(info.getCoalStorage().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
        }
        map.put("detail", listInfo);
        List<repertoryInfo> list = groupStatisticMapper.inventoryCount();
        for (repertoryInfo l : list) {
            l.setCompanyName(l.getCompanyType().equals("0") ? "煤业公司" : l.getCompanyType().equals("1") ? "北方公司" : "蒙东公司");
        }
        map.put("statistics", list);
        return map;
    }
}
